package com.zyw.shiro;


import com.zyw.entity.User;
import com.zyw.service.user.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    public static void main(String[] args) {
        System.out.println(new Md5Hash("123123","qwersofdandahfownviwneif",1024));
    }


    //创建对象时自动set进对象里
    {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //加密方式是
        matcher.setHashAlgorithmName("MD5");
        //加密次数是
        matcher.setHashIterations(1024);

        this.setCredentialsMatcher(matcher);
    }
    @Override
    //授权    查询用户的角色和权限
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //获取当前登录用户的用户名
        User user = (User) principals.getPrimaryPrincipal();
        String username = user.getUsername();
        //根据用户名查询全部角色信息
        Set<String> roleNames=userService.findRolesByUsername(username);
        //根据角色信息查询全部权限信息
        Set<String> permissions =userService.findPermissionsByRoles(roleNames);
        //创建返回结果SimpleAuthorizationInfo，并封装角色和权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
        info.setStringPermissions(permissions);
        return info;
    }



    @Override
    //认证    判断用户是否登录过
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户输入的用户名
        String username = (String) token.getPrincipal();
        //根据用户名信息查询用户信息
        User user = userService.findByUsername(username);
        //判断用户信息是否为空
        if (user==null){
            //跳转到登录页面
            return null;
        }
        //将正确的user对象和密码封装到AuthenticationInfo对象中
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),"realmName");
        //*******注意盐也要封装到AuthenticationInfo对象中*****
        info.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
        return info;
    }


}
